/*
 * RegUserAuthManager.cpp
 *
 *  Created on: 2015年7月16日
 *      Author: terry
 */

#include "RegUserAuthManager.h"

#include <rutil/MD5Stream.hxx>


RegUserAuthManager::RegUserAuthManager(DialogUsageManager& dum,
        RegUserStore& userStore, const resip::Data& staticRealm):
	ServerAuthManager(dum, dum.dumIncomingTarget(), true, staticRealm),
	m_userStore(userStore)
{
}

RegUserAuthManager::~RegUserAuthManager()
{
}

void RegUserAuthManager::requestCredential(const Data& user,
                                   const Data& realm,
                                   const SipMessage& msg,
                                   const Auth& auth, // the auth line we have chosen to authenticate against
                                   const Data& transactionToken)
{
    //UserAuthInfo::InfoMode mode = UserAuthInfo::UserUnknown;
    UserAuthInfo* authInfo = new UserAuthInfo(user, realm, transactionToken, &mDum);

    RegUser userInfo;
    if (m_userStore.find(user.c_str(), userInfo))
    {
        //authInfo->setMode(UserAuthInfo::DigestNotAccepted);
        resip::MD5Stream a1;
        a1 << user
            << resip::Symbols::COLON
            << realm
            << resip::Symbols::COLON
            << userInfo.password;
        a1.flush();

        authInfo->setA1(a1.getHex());
    }

    mDum.post(authInfo);
}

bool RegUserAuthManager::proxyAuthenticationMode() const
{
    return false;
}

bool RegUserAuthManager::authorizedForThisIdentity(const resip::Data &user, 
                                       const resip::Data &realm, 
                                       resip::Uri &fromUri)
{
    return true;
}

ServerAuthManager::Result RegUserAuthManager::handle(SipMessage* sipMsg)
{
    if (sipMsg->isRequest())
    {
        if(sipMsg->method() == REGISTER)
        {
            return ServerAuthManager::handle(sipMsg);
        }
    }

    return Skipped;
}